import { useEffect } from "react";
import { Space, Popconfirm, Table, message, Form, Select, Divider } from "antd";
import { ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconDelete } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";

import useUpdateApplication from "../../hooks/application/organization/useUpdateApplication";
import { useOrganizationDatabase } from "../../hooks/databases";

const DependentedDatabases = ({ application, reloadData }) => {
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent } = useModel("global.modal");
    const { loadDatabases, databases } = useOrganizationDatabase();
    const { updateApplication } = useUpdateApplication();

    const state = useReactive({
        loading: false,
        submitLoading: false,
        appDatabases: application.appData || [],
    });

    useEffect(() => {
        loadDatabases();
    }, []);

    useEffect(() => {
        state.appDatabases = application.appData || [];
    }, [application]);

    const addDatabase = async (appData) => (state.appDatabases = appData);

    const openAddDatabaseModal = async () => {
        let newData = databases.filter((item) => state.appDatabases.findIndex((_item) => item.databaseName === _item.databaseName) === -1);
        setModalTitle("添加依赖的数据库");
        setModalWidth(750);
        setModalComponent(<AddDependentedDatabase application={application} databases={newData} addDatabase={addDatabase} reloadData={reloadData} />);
        setModalVisible(true);
    };

    const openUpdateDatabaseModal = async (record, index) => {
        setModalTitle("更改依赖的数据库模型版本");
        setModalWidth(750);
        setModalComponent(
            <UpdateDatabaseVersion application={application} index={index} database={record} appData={state.appDatabases} updateDatabases={addDatabase} reloadData={reloadData} />
        );
        setModalVisible(true);
    };

    const removeDatabase = async (record) => {
        let appData = state.appDatabases.filter((item) => item.uuid !== record.uuid);
        let variables = {
            appUpti: new Date().getUTCTime(),
            appData,
        };
        updateApplication(application.appUuid, variables, (res) => {
            if (res) {
                message.success("成功更新应用信息");
                addDatabase(appData);
                reloadData && reloadData();
            }
        });
    };

    const TableHeader = () => {
        return (
            <div style={{ display: "flex", justifyContent: "space-between" }}>
                <div style={{ lineHeight: "32px" }}>依赖的数据库模型信息</div>
                <ButtonGroup>
                    <Button icon={<IconPlusCircle />} onClick={openAddDatabaseModal}>
                        添加依赖的数据库模型
                    </Button>
                </ButtonGroup>
            </div>
        );
    };

    return (
        <Table loading={state.loading} title={TableHeader} dataSource={state.appDatabases || []} rowKey="uuid" size="small" bordered pagination={false}>
            <Table.Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
            <Table.Column title="数据库模型名称" dataIndex="databaseName" align="left" />
            <Table.Column title="数据库模型说明" dataIndex="title" align="left" />
            <Table.Column
                title="数据库模型版本号"
                dataIndex="versionNo"
                align="center"
                render={(_, r, i) => (
                    <Button theme="borderless" onClick={() => openUpdateDatabaseModal(r, i)}>
                        {_}
                    </Button>
                )}
            />
            <Table.Column
                title="操作"
                align="center"
                width={120}
                render={(_, r) => (
                    <Space size={0} split={<Divider type="vertical" />}>
                        <Popconfirm
                            title="确认要移除该依赖的数据库信息吗?"
                            okButtonProps={{
                                loading: state.submitLoading,
                            }}
                            placement="topRight"
                            onConfirm={() => removeDatabase(r)}
                        >
                            <Button theme="borderless" icon={<IconDelete style={{ color: "#E91E63" }} />}></Button>
                        </Popconfirm>
                    </Space>
                )}
            />
        </Table>
    );
};

const AddDependentedDatabase = ({ application, databases, addDatabase, reloadData }) => {
    const { onCloseGlobalModal } = useModel("global.modal");
    const [form] = Form.useForm();
    const { updateApplication } = useUpdateApplication();
    const { loadDatabaseVersionsByDatabaseName, versions, versionLoading } = useOrganizationDatabase();

    const state = useReactive({
        submitLoading: false,
        databaseName: "",
        selectedDatabase: null,
    });

    useEffect(() => {
        if (state.databaseName) {
            form.setFieldValue("version", "");
            loadDatabaseVersionsByDatabaseName(state.databaseName);
        }
    }, [state.databaseName]);

    const onFinish = async (values) => {
        let appData = application.appData;
        let newData = {
            uuid: state.selectedDatabase.uuid,
            title: state.selectedDatabase.title,
            ...values,
        };
        let index = appData.findIndex((item) => item.databaseName === values.databaseName);
        if (index === -1) {
            appData.push(newData);
        } else {
            appData[index] = newData;
        }
        let variables = {
            appUpti: new Date().getUTCTime(),
            appData,
        };
        updateApplication(application.appUuid, variables, (res) => {
            if (res) {
                message.success("成功更新应用信息");
                addDatabase(appData);
                reloadData && reloadData();
                onCloseGlobalModal();
            }
        });
    };

    return (
        <div style={{ padding: 20 }}>
            <Form form={form} onFinish={onFinish} layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                <Form.Item label="数据库模型名称" name="databaseName" rules={[{ required: true, message: "请选择数据库模型名称" }]}>
                    <Select
                        allowClear
                        onSelect={(value) => {
                            state.databaseName = value;
                            state.selectedDatabase = databases.find((item) => item.databaseName === value);
                        }}
                    >
                        {databases.map((item, index) => (
                            <Select.Option key={index} value={item.databaseName}>
                                {item.title} - {item.databaseName}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>

                <Form.Item label="数据库模型版本" name="versionNo" rules={[{ required: true, message: "请选择数据库模型版本" }]}>
                    <Select allowClear loading={versionLoading}>
                        {versions.map((item, index) => (
                            <Select.Option key={index} value={item.versionNo}>
                                {item.versionNo}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>

                <div style={{ textAlign: "center" }}>
                    <Space>
                        <Button loading={state.submitLoading} type="primary" htmlType="submit">
                            添加
                        </Button>
                        <Button loading={state.submitLoading} htmlType="button" onClick={() => form.resetFields()}>
                            重置
                        </Button>
                    </Space>
                </div>
            </Form>
        </div>
    );
};

const UpdateDatabaseVersion = ({ application, index, database, appData, updateDatabases, reloadData }) => {
    const [form] = Form.useForm();
    const { onCloseGlobalModal } = useModel("global.modal");
    const { updateApplication } = useUpdateApplication();
    const { loadDatabaseVersionsByDatabaseName, versions, versionLoading } = useOrganizationDatabase();

    const state = useReactive({
        submitLoading: false,
        databaseName: "",
        selectedDatabase: null,
    });

    useEffect(() => {
        if (database.databaseName) {
            loadDatabaseVersionsByDatabaseName(database.databaseName);
        }
    }, [database.databaseName]);

    const onFinish = (values) => {
        appData[index].versionNo = values.versionNo;
        updateApplication(application.appUuid, { appData }, (res) => {
            if (res) {
                message.success("成功更新应用信息");
                updateDatabases(appData);
                reloadData && reloadData();
                onCloseGlobalModal();
            }
        });
    };

    return (
        <Form form={form} onFinish={onFinish} layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} style={{ padding: 20 }}>
            <Form.Item label="数据库模型说明">{database.title}</Form.Item>

            <Form.Item label="数据库模型名称">{database.databaseName}</Form.Item>

            <Form.Item label="数据库模型版本" name="versionNo" rules={[{ required: true, message: "请选择数据库模型版本" }]}>
                <Select allowClear loading={versionLoading}>
                    {versions.map((item, index) => (
                        <Select.Option key={index} value={item.versionNo}>
                            {item.versionNo}
                        </Select.Option>
                    ))}
                </Select>
            </Form.Item>

            <div style={{ textAlign: "center" }}>
                <Space>
                    <Button loading={state.submitLoading} type="primary" htmlType="submit">
                        更新
                    </Button>
                    <Button loading={state.submitLoading} htmlType="button" onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </div>
        </Form>
    );
};

export default DependentedDatabases;
